﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using thinger.ModbusLib;

namespace thinger.ModbusProject
{
    public partial class Form1 : Form
    {
        private ModbusRTU modbusRTU = new ModbusRTU();

        private Timer updateTimer = new Timer();

        public Form1()
        {
            InitializeComponent();

            updateTimer.Interval = 500;
            updateTimer.Tick += UpdateTimer_Tick;

            // 建立连接
            bool result = modbusRTU.Connect("COM20", 9600, Parity.None, 8, StopBits.One);

            if (result)
            {
                // 启动定时器
                updateTimer.Start();
            }
            else
            {
                MessageBox.Show("连接出错");
            }
        }

        private void UpdateTimer_Tick(object sender, EventArgs e)
        {
            // 实时读取
            byte[] data = modbusRTU.ReadOutputRegisters(1, 0, 1);

            // 因为只读取一个寄存器,所以data.Length只能是2字节
            // 如果是2个字节(A和B),要转换为2字节的整型的话,那么A*256+B=C
            if (data != null && data.Length == 2)
            {
                this.lbl_40001.Text = (data[0] * 256 + data[1]).ToString();
            }
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 关闭定时器
            this.updateTimer.Stop();
            // 断开串口
            modbusRTU.DisConnect();
        }
    }
}
